//
//  TWRootViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/4/18.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh

let FromRootVc = "FromRootVc"

class TWRootViewController: UITableViewController {

    // 数据源
    fileprivate lazy var dataArray : NSMutableArray = NSMutableArray()
    fileprivate lazy var nextPageUrl : String = String()                                    // 下一页网址
    fileprivate lazy var footerView : TWFooterView = TWFooterView.createFooterView()        // 脚部视图
    fileprivate lazy var footerNullView : UILabel = UILabel()                               // 空的脚部视图
    
    var isFooterRefreshing : Bool = false
    
    var urlString : String?{
        didSet {
            guard let _ = urlString else {
                return
            }
            setupRefresh()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupTableView()
        setupNullFooter()
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(discoverViewControllerTabBarButtonDidRepeatClick), name: NSNotification.Name(rawValue: TabBarButtonDidRepeatClickNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(detailCollectionViewCellDidClick(note:)), name: NSNotification.Name(rawValue: DetailCollectionViewCellDidClickNotification), object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:- UI相关
extension TWRootViewController {
    fileprivate func setupRefresh(){
        tableView.mj_header = TWRefreshHeader(refreshingTarget: self, refreshingAction: #selector(refreshLoadNewData))
        tableView.mj_header.isAutomaticallyChangeAlpha = true
        tableView.mj_header.beginRefreshing()
    }
    fileprivate func setupTableView(){
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: NavigationBarHeight + DiscovertitleViewHeight, left: 0, bottom: TabBarHeight, right: 0)
        tableView.scrollIndicatorInsets = tableView.contentInset
        
        // 注册
        tableView.register(UINib(nibName: "TWBannerCell", bundle: nil), forCellReuseIdentifier: BannerCell)
        tableView.register(UINib(nibName: "TWFooterCell", bundle: nil), forCellReuseIdentifier: FooterCell)
        tableView.register(UINib(nibName: "TWHeaderCell", bundle: nil), forCellReuseIdentifier: HeaderCell)
        tableView.register(UINib(nibName: "TWTextCardCell", bundle: nil), forCellReuseIdentifier: TextCardCell)
        tableView.register(UINib(nibName: "TWBriefCardCell", bundle: nil), forCellReuseIdentifier: BriefCardCell)
        tableView.register(UINib(nibName: "TWBlankCardCell", bundle: nil), forCellReuseIdentifier: BlankCardCell)
        tableView.register(UINib(nibName: "TWChoicenessItemCell", bundle: nil), forCellReuseIdentifier: VideoCell)
        tableView.register(UINib(nibName: "TWItemCollectionCell", bundle: nil), forCellReuseIdentifier: ItemCollectionCell)
        tableView.register(UINib(nibName: "TWSquareCardCollectionCell", bundle: nil), forCellReuseIdentifier: SquareCardTableViewCell)
        tableView.register(UINib(nibName: "TWHorizontalScrollCardCell", bundle: nil), forCellReuseIdentifier: HorizontalScrollCardCell)
        tableView.register(UINib(nibName: "TWVideoCollectionWithBrief", bundle: nil), forCellReuseIdentifier: VideoCollectionWithBrief)
        tableView.register(UINib(nibName: "TWVideoCollectionOfFollowCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfFollowCell)
        tableView.register(UINib(nibName: "TWVideoCollectionOfAuthorWithCoverCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfAuthorWithCoverCell)
        tableView.register(UINib(nibName: "TWVideoCollectionOfHorizontalScrollCardCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfHorizontalScrollCard)
    }
    fileprivate func setupNullFooter(){
        // 没有数据时的tableFooterView
        footerNullView = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
        footerNullView.text = "-end-"
        footerNullView.font = UIFont.init(name: "Lobster1.4", size: 15)
        footerNullView.textAlignment = .center
    }
}

// MARK:- 监听点击
extension TWRootViewController {
    @objc fileprivate func discoverViewControllerTabBarButtonDidRepeatClick(){
        if tableView.scrollsToTop == false {
            return
        }
        tableView.mj_header.beginRefreshing()
    }
    @objc fileprivate func refreshLoadNewData(){
        loadNewRootData(urlString: urlString!)
    }
    @objc fileprivate func refreshLoadMoreData(){
        loadMoreRootData()
    }
    @objc fileprivate func detailCollectionViewCellDidClick(note : NSNotification){
        let dict = note.object as! [String : AnyObject]
        if dict.keys.first == FromRootVc {
            let selectModel = dict.values.first as! TWItemModel // 拿到当前选中的模型
            let animationViewController : TWAnimationViewController = TWAnimationViewController()
            animationViewController.itemModel = selectModel
            present(animationViewController, animated: true, completion: nil)
        }
    }
}

// MARK:- 请求数据
extension TWRootViewController {
    /// 请求最新网络数据
    fileprivate func loadNewRootData(urlString : String){
        loadingAuthorData(isLoadNewData: true, urlString: urlString)
    }
    /// 加载更多数据
    fileprivate func loadMoreRootData(){
        loadingAuthorData(isLoadNewData: false, urlString: nextPageUrl)
    }
    
    private func loadingAuthorData(isLoadNewData : Bool, urlString : String){
        TWNetworkTool.shareInstance.loadDiscoverViewData(urlString: urlString) { (result, error) in
            if error != nil {
                self.tableView.mj_header.endRefreshing()
                self.footerEndRefresh()
                SVProgressHUD.showError(withStatus: "加载失败！")
            }
            guard let result = result else {
                return
            }
            let next = result["nextPageUrl"]
            if String(describing: next!) == "<null>" {
                self.footerEndRefresh()
                self.tableView.tableFooterView = self.footerNullView
                return
            } else {
                self.nextPageUrl = next as! String
            }
            // 处理cell相关的数据
            self.dealWithData(isLoadNewData : isLoadNewData, result: result)
        }
    }
    private func dealWithData(isLoadNewData : Bool, result : [String : AnyObject]){
        // 需要展示主体数据的数组
        let itemListArray = result["itemList"] as! [[String : AnyObject]]
        let tempArray : NSMutableArray = NSMutableArray()
        // 遍历数组,判断是什么类型，转成模型
        for item in itemListArray {
            let dataType = item["type"] as! String
            // dataType一共有14种类型,根据类型不同分别转成不同的模型
            switch dataType {
            case video:
                let itemModel : TWItemModel = TWItemModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([video : itemModel])
            case textFooter:
                let itemModel : TWTextFooterModel = TWTextFooterModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([textFooter : itemModel])
            case textHeader:
                let itemModel : TWTextHeaderModel = TWTextHeaderModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([textHeader : itemModel])
            case videoCollectionWithCover:
                let itemModel : TWItemCollectionModel = TWItemCollectionModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionWithCover : itemModel])
            case videoCollectionOfFollow:
                let itemModel : TWVideoCollectionOfFollowModel = TWVideoCollectionOfFollowModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionOfFollow : itemModel])
            case squareCardCollection:
                let itemModel : TWSquareCardCollectionModel = TWSquareCardCollectionModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([squareCardCollection : itemModel])
            case videoCollectionOfAuthorWithCover:
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionOfAuthorWithCover : itemModel])
            case banner:
                let itemModel : TWBannerModel = TWBannerModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([banner : itemModel])
            case horizontalScrollCard:
                let itemModel : TWHorizontalScrollCard = TWHorizontalScrollCard(dict: item["data"] as! [String : AnyObject])
                tempArray.add([horizontalScrollCard : itemModel])
            case VideoCollectionWithBrief:
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionWithBrief : itemModel])
            case VideoCollectionOfHorizontalScrollCard :
                let itemModel : TWVideoCollectionOfHorizontalScrollCardModel = TWVideoCollectionOfHorizontalScrollCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionOfHorizontalScrollCard : itemModel])
            case TextCard :
                let itemModel : TWTextCardModel = TWTextCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([TextCard : itemModel])
            case BriefCard :
                let itemModel : TWBriefCardModel = TWBriefCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([BriefCard : itemModel])
            case BlankCard :
                let itemModel : TWBlankCardModel = TWBlankCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([BlankCard : itemModel])
            default:
                TWLog(message: "又有一组其他类型的数据")
            }
        }
    
        if isLoadNewData {
            dataArray.removeAllObjects()
            for item in tempArray {
                dataArray.add(item)
            }
        } else {
            for item in tempArray {
                dataArray.add(item)
            }
        }
        // 刷新UI
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.tableView.reloadData()
            self.tableView.tableFooterView = self.footerView
            self.tableView.mj_header.endRefreshing()
            self.footerEndRefresh()
            SVProgressHUD.dismiss()
        }
    }
}

// MARK: - TableView代理方法
extension TWRootViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 取出当前对应的类型
        let data = dataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        switch key {
        case video:
            return VideoCellHeight
        case textFooter:
            return headerFooterCellHeight
        case textHeader:
            return headerFooterCellHeight
        case videoCollectionWithCover:
            return VideoCollectionCellHeight
        case videoCollectionOfFollow:
            return VideoCollectionCellHeight
        case squareCardCollection:
            return squareCardCellHeight
        case videoCollectionOfAuthorWithCover:
            return VideoCollectionCellHeight
        case banner:
            return VideoCellHeight
        case horizontalScrollCard:
            return VideoCellHeight
        case VideoCollectionWithBrief :
            return videoCollectionWithBriefCellHeight
        case VideoCollectionOfHorizontalScrollCard :
            return videoCollectionOfHorizontalScrollCardCellHeight
        case TextCard :
            return TextCardHeight
        case BriefCard :
            return BriefCardHeight
        case BlankCard :
            return BlankCardHeight
        default:
            return 0
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 取出当前对应的类型
        let data = dataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        switch key {
        case video:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCell, for: indexPath) as! TWChoicenessItemCell
            cell.selectionStyle = .none
            let itemModel = data.values.first as! TWItemModel
            cell.itemModel = itemModel
            return cell
        case textFooter:
            let cell = tableView.dequeueReusableCell(withIdentifier: FooterCell, for: indexPath) as! TWFooterCell
            cell.selectionStyle = .none
            let textFooter = data.values.first as! TWTextFooterModel
            cell.textFooter = textFooter
            return cell
        case textHeader:
            let cell = tableView.dequeueReusableCell(withIdentifier: HeaderCell, for: indexPath) as! TWHeaderCell
            cell.selectionStyle = .none
            let textHeader = data.values.first as! TWTextHeaderModel
            cell.textHeader = textHeader
            return cell
        case videoCollectionWithCover:
            let cell = tableView.dequeueReusableCell(withIdentifier: ItemCollectionCell, for: indexPath) as! TWItemCollectionCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWItemCollectionModel
            cell.itemCollectionModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromRootVc
            return cell
        case videoCollectionOfFollow:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfFollowCell, for: indexPath) as! TWVideoCollectionOfFollowCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfFollowModel
            cell.videoCollectionOfFollowModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromRootVc
            return cell
        case squareCardCollection:
            let cell = tableView.dequeueReusableCell(withIdentifier: SquareCardTableViewCell, for: indexPath) as! TWSquareCardCollectionCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWSquareCardCollectionModel
            cell.squareCardCollectionModel = itemCollectionModel
            return cell
        case videoCollectionOfAuthorWithCover:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfAuthorWithCoverCell, for: indexPath) as! TWVideoCollectionOfAuthorWithCoverCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.VideoCollectionOfAuthorWithCoverModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromRootVc
            return cell
        case banner:
            let cell = tableView.dequeueReusableCell(withIdentifier: BannerCell, for: indexPath) as! TWBannerCell
            cell.selectionStyle = .none
            let bannerModel = data.values.first as! TWBannerModel
            cell.bannerModel = bannerModel
            return cell
        case horizontalScrollCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: HorizontalScrollCardCell, for: indexPath) as! TWHorizontalScrollCardCell
            cell.selectionStyle = .none
            let horizontalScrollCardCellModel = data.values.first as! TWHorizontalScrollCard
            cell.horizontalScrollCardModel = horizontalScrollCardCellModel
            cell.horizontalScrollCardCellDelegate = self
            return cell
        case VideoCollectionWithBrief:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionWithBrief, for: indexPath) as! TWVideoCollectionWithBrief
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.model = itemCollectionModel
            cell.bottomCollectionView.fromWhichVc = FromRootVc
            cell.videoCollectionWithBriefDelegate = self
            return cell
        case VideoCollectionOfHorizontalScrollCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfHorizontalScrollCard, for: indexPath) as! TWVideoCollectionOfHorizontalScrollCardCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfHorizontalScrollCardModel
            cell.model = itemCollectionModel
            cell.horizontalScrollCardCellDelegate = self
            cell.bottomCollectionView.fromWhichVc = FromRootVc
            return cell
        case TextCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: TextCardCell, for: indexPath) as! TWTextCardCell
            cell.selectionStyle = .none
            let model = data.values.first as! TWTextCardModel
            cell.model = model
            return cell
        case BriefCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: BriefCardCell, for: indexPath) as! TWBriefCardCell
            cell.selectionStyle = .none
            let model = data.values.first as! TWBriefCardModel
            cell.model = model
            return cell
        case BlankCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: BlankCardCell, for: indexPath) as! TWBlankCardCell
            cell.selectionStyle = .none
            return cell
        default:
            return UITableViewCell()
        }
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 取出当前对应的类型
        let data = dataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        if key == video {
            let itemModel = data.values.first as! TWItemModel
            let animationViewController : TWAnimationViewController = TWAnimationViewController()
            animationViewController.modalPresentationStyle = .custom
            animationViewController.itemModel = itemModel
            present(animationViewController, animated: true, completion: nil)
        } else if key == textFooter {
            let itemModel = data.values.first as! TWTextFooterModel
            TWLog(message: itemModel.text)
        }
    }
}

// MARK:- HorizontalScrollCardCellDelegate代理方法
extension TWRootViewController : HorizontalScrollCardCellDelegate {
    func cycleScrollViewDidSelectItemAt(selectedItem: TWBannerModel) {
        TWLog(message: selectedItem.title)
    }
}

// MARK:- VideoCollectionWithBriefDelegate的代理方法
extension TWRootViewController : VideoCollectionWithBriefDelegate {
    func pushViewControllerWith(model: TWVideoCollectionOfAuthorWithCoverModel) {
        let briefViewController : TWBriefViewController = TWBriefViewController()
        briefViewController.model = model
        self.navigationController?.pushViewController(briefViewController, animated: true)
    }
}

// MARK:- VideoCollectionOfHorizontalScrollCardCellDelegate的代理方法
extension TWRootViewController : VideoCollectionOfHorizontalScrollCardCellDelegate {
    func horizontalScrollCardCellTitleDidClick(model: TWVideoCollectionOfHorizontalScrollCardModel) {
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.red
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK:- scrollView的代理方法
extension TWRootViewController {
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let insetTop = NavigationBarHeight
        // 滚动偏移量
        let offset = -(tableView.contentOffset.y + insetTop)  // 默认为0
        dealFooter(offset: offset)
    }
}

// MARK:- 刷新相关的方法
extension TWRootViewController {
    fileprivate func dealFooter(offset : CGFloat){
        // 还没有任何内容的时候，不需要判断
        if tableView.contentSize.height == 0 {
            return
        }
        if isFooterRefreshing {
            return
        }
        // 计算偏移量 = 内容的顶部和frame的顶部的差值,tableView.contentSize包括header和footer
        let ofsetY = tableView.contentSize.height + tableView.contentInset.bottom - tableView.frame.height
        if tableView.contentOffset.y >= ofsetY && self.tableView.contentOffset.y > -(self.tableView.contentInset.top) {
            footerBeginRefresh()
        }
    }
    // MARK:- 刷新相关
    func footerBeginRefresh() {
        if isFooterRefreshing {
            return
        }
        // 进入刷新状态
        isFooterRefreshing = true
        footerView.addRotationAnimation()
        loadMoreRootData()
    }
    func footerEndRefresh() {
        isFooterRefreshing = false
        footerView.loading_in_ImageView.layer.removeAllAnimations()
    }
}

